import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { customers } from '@/lib/schema';

interface CustomerData {
  name: string;
  email: string;
  phone?: string;
  phone2?: string;
  phone2Purpose?: string;
  wechat?: string;
  wechatPurpose?: string;
  qq?: string;
  qqPurpose?: string;
  whatsapp?: string;
  whatsappPurpose?: string;
  telegram?: string;
  telegramPurpose?: string;
  address?: string;
  company?: string;
}

export async function POST(request: NextRequest) {
  try {
    const customerData: CustomerData[] = await request.json();
    
    if (!Array.isArray(customerData) || customerData.length === 0) {
      return NextResponse.json(
        { error: '请提供有效的客户数据数组' },
        { status: 400 }
      );
    }

    // 验证数据格式
    for (const customer of customerData) {
      if (!customer.name || !customer.email) {
        return NextResponse.json(
          { error: '每个客户必须包含姓名和邮箱' },
          { status: 400 }
        );
      }
    }

    // 检查邮箱是否已存在
    const existingEmails = await db
      .select({ email: customers.email })
      .from(customers);
    
    const existingEmailSet = new Set(existingEmails.map(item => item.email));
    const duplicateEmails = customerData
      .filter(customer => existingEmailSet.has(customer.email))
      .map(customer => customer.email);
    
    if (duplicateEmails.length > 0) {
      return NextResponse.json(
        { 
          error: '以下邮箱已存在',
          duplicateEmails 
        },
        { status: 409 }
      );
    }

    // 批量插入客户数据
    const insertedCustomers = await db
      .insert(customers)
      .values(customerData.map(customer => ({
        name: customer.name,
        email: customer.email,
        phone: customer.phone || null,
        phone2: customer.phone2 || null,
        phone2Purpose: customer.phone2Purpose || null,
        wechat: customer.wechat || null,
        wechatPurpose: customer.wechatPurpose || null,
        qq: customer.qq || null,
        qqPurpose: customer.qqPurpose || null,
        whatsapp: customer.whatsapp || null,
        whatsappPurpose: customer.whatsappPurpose || null,
        telegram: customer.telegram || null,
        telegramPurpose: customer.telegramPurpose || null,
        address: customer.address || null
      })))
      .returning();

    return NextResponse.json({
      message: `成功导入 ${insertedCustomers.length} 个客户`,
      importedCount: insertedCustomers.length,
      customers: insertedCustomers
    }, { status: 201 });

  } catch (error: any) {
    console.error('批量导入客户失败:', error);
    
    if (error.message?.includes('UNIQUE constraint failed')) {
      return NextResponse.json(
        { error: '导入失败：邮箱地址必须唯一' },
        { status: 409 }
      );
    }
    
    return NextResponse.json(
      { error: '批量导入客户失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    // 获取示例数据
    const fs = await import('fs');
    const path = await import('path');
    
    const dataPath = path.join(process.cwd(), 'data', 'customers-seed2.json');
    const seedData = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
    
    return NextResponse.json({
      sampleData: seedData,
      count: seedData.length,
      description: '示例客户数据，可用于批量导入测试'
    });
    
  } catch (error) {
    console.error('获取示例数据失败:', error);
    return NextResponse.json(
      { 
        error: '获取示例数据失败',
        message: '请确保data/customers-seed.json文件存在'
      },
      { status: 500 }
    );
  }
}